<?php

namespace app\admin\controller;
use app\admin\model\CostConfig as CostConfigModel;
use app\admin\model\RegionModel;
use think\Db;
use think\Env;
use my\Tools;

class CostConfig extends Base {

    protected $cost_config_model;
    protected $region_model;

    public function _initialize() {
        parent::_initialize();
        $this->cost_config_model = new CostConfigModel();
        $this->region_model = new RegionModel();
        $provinceList = $this->region_model->getRegion(['parent_id'=>1,'region_level'=>1],'region_id,region_name');
        $this->assign('provinceList',$provinceList);
    }

    /**
     * 费用配置列表
     * @param string
     * @param int
     * @return string
     */
    public function index() {
        $page = input('get.page');
        $limit = input('get.limit');
        if ($page && $limit) {
            $data = input('get.');
            $list = $this->cost_config_model->getListInfo($page, $limit, $data);
            echo json_encode($list);
            exit;
        }
        return $this->fetch();
    }
    
    //删除费用配置
    /*public function del() {
        if (input('get.id')) {
            $id = input('get.id');
            $data = Db::name('cost_config')->where('id',$id)->update(['status'=>0]);
            if ($data) {
                exit(json_encode(['status' => 1, 'msg' => '删除成功']));
            } else {
                exit(json_encode(['status' => 0, 'msg' => '删除失败']));
            }
        } else {
            $this->error('不存在的费用信息', '', '', 1);
        }
    }*/
    
    //添加营运城市
    public function add() {
        if (input('post.')) {
            $data = input('post.');
            if ($data['user_cancel_fee']){
                $data['user_cancel_fee']=$data['user_cancel_fee']*100;
            }
            //查询当前运营城市是否存在
            $priceRuleInfo = Db::name('price_rule')->where(['province_id'=>$data['province_id'],'city_id'=>$data['city_id'],'status'=>1])->find();
            if(!empty($priceRuleInfo)){
                return "<script type='application/javascript'>alert('该区域已存在,请勿重复添加');parent.window.location.reload();</script>";
            }
            if(strlen(trim($data['first_name'])) > 1){
                return "<script type='application/javascript'>alert('首字母只能输入一个字母');parent.window.location.reload();</script>";
            }
            //查询省份名称
            if(!empty($data['province_id'])){
                $data['province_name']   = Db::name('region')->where('region_id', $data['province_id'])->value('region_name');
            }else{
                $data['province_name']   = "默认省份";
            }
            //获取城市名称
            if(!empty($data['city_id'])){
                $data_city = Db::name('region')->field('region_name,region_code')->where('region_id', $data['city_id'])->find();
                $data['city_name'] = $data_city['region_name'];
                $data['region_code'] = $data_city['region_code'];
            }else{
                $data['city_name']      = "默认城市";
            }
            //如果省份 - 城市都为空 则为默认模板
            if(empty($data['province_id']) && empty($data['city_id'])){
                $data['is_default']     = 1;
            }
            //选择省份 生成所有城市数据
            $regionList = [];
            if(!empty($data['province_id']) && empty($data['city_id'])){
                //查询所有城市
                $regionList = Db::name('region')->where('parent_id', $data['province_id'])->select();
            }
            //自定义取消规则开启 0未开启1开启
            if(empty($data['is_cancel'])){
                $data['is_cancel'] = 0;
            }
            //自定义计价是否开启 0未开启1开启
            if(empty($data['is_valuation'])){
                $data['is_valuation'] = 0;
            }
            //异地接单 0未开启1开启
            if(empty($data['remote_order'])){
                $data['remote_order'] = 0;
            }
            //$data['real_cancel_time']   = $data['real_cancel_time']*60;     //司机出发去接乘客 等待时间 - 实时
            //$data['real_arrive_time']   = $data['real_arrive_time']*60;     //司机到达乘客起点 等待时间 - 实时
            //$data['book_cancel_time']   = $data['book_cancel_time']*60;     //司机出发去接乘客 等待时间 - 预约
            //$data['book_start_time']    = $data['book_start_time']*60;      //距离预约出发时间不足 等待时间 - 预约
            //$data['book_arrive_time']   = $data['book_arrive_time']*60;     //司机到达乘客起点 等待时间 - 预约
            //$data['book_over_time']     = $data['book_over_time']*60;       //超过预约出发时间 等待时间 - 预约

            //$data['real_cancel_fee']    = $data['real_cancel_fee']*100;     //司机出发去接乘客 有责取消费用 - 实时
            //$data['real_arrive_fee']    = $data['real_arrive_fee']*100;     //司机到达乘客起点 有责取消费用 - 实时
            //$data['book_cancel_fee']    = $data['book_cancel_fee']*100;     //司机出发去接乘客 有责取消费用 - 预约
            //$data['book_start_fee']     = $data['book_start_fee']*100;      //距离预约出发时间不足 有责取消费用 - 预约
            //$data['book_arrive_fee']    = $data['book_arrive_fee']*100;     //司机到达乘客起点 有责取消费用 - 预约
            //$data['book_over_fee']      = $data['book_over_fee']*100;       //超过预约出发时间 有责取消费用 - 预约

            //时间转换成秒
            $data['start_time']         = $data['start_time']*60;           //起步时长
            $data['free_wait_time']     = $data['free_wait_time']*60;       //免费等待时长
            $data['leave_time']         = $data['leave_time']*60;           //司机出发时长
            $data['arrive_time']        = $data['arrive_time']*60;          //司机到达时长
            $data['book_remain_time']   = $data['book_remain_time']*60;     //预约时间剩余时长
            //费用转换成分
            $data['low_fee']            = $data['low_fee']*100;             //有责取消费用（低）
            $data['high_fee']           = $data['high_fee']*100;            //有责取消费用（高）
            $data['start_fee']          = $data['start_fee']*100;           //起步价
            $data['mileage_fee']        = $data['mileage_fee']*100;         //里程费
            $data['time_fee']           = $data['time_fee']*100;            //时长费
            $data['over_wait_fee']      = $data['over_wait_fee']*100;       //超时等待费
            $data['over_wait_fee_max']  = $data['over_wait_fee_max']*100;   //超时等待费上限
            //里程转换成米
            $data['start_mileage']      = $data['start_mileage']*1000;      //起步里程
            $data['admin_id']           = session('admin_id');
            $data['add_time']           = time();
            if(empty($regionList)){
                $rule_id = Db::name('price_rule')->insertGetId($data);
                self::priceRule($data,$rule_id);                            //计价规则 + 远途费
            }else{
                $releArr = [];
                foreach ($regionList as $key=>$value){
                    $priceRuleInfo = Db::name('price_rule')->where(['city_id'=>$value['region_id'],'status'=>1])->find();//查询城市名称
                    if(empty($priceRuleInfo)){
                        $data['city_id']        = $value['region_id'];              //城市ID
                        $data['first_name']     = $value['region_first_name_en'];   //城市首字母
                        $data['city_name']      = $value['region_name'];            //城市名称
                        $rule_id = Db::name('price_rule')->insertGetId($data);
                        if($rule_id){
                            $releArr[] = $rule_id;
                            self::priceRule($data,$rule_id);                    //计价规则 + 远途费
                        }
                    }
                }
                //交通部数据 提交到java
                $type = 'add';
//                $this->cost_config_to_java($data,$type);
            }
            return "<script type='application/javascript'>parent.window.location.reload();</script>";

        } else {
            return view();
        }
    }

    //修改费用配置
    public function edit() {
        if (input('post.')) {
            $data = input('post.');
            if ($data['user_cancel_fee']){
                $data['user_cancel_fee']=$data['user_cancel_fee']*100;
            }
            //查询当前运营城市是否存在
            $priceRuleInfo = Db::name('price_rule')->where(['province_id'=>$data['province_id'],'city_id'=>$data['city_id'],'status'=>1,'id'=>['<>',$data['id']]])->find();
            if(!empty($priceRuleInfo)){
                return "<script type='application/javascript'>alert('该区域已存在,请勿重复添加');parent.window.location.reload();</script>";
            }
            if(strlen(trim($data['first_name'])) > 1){
                return "<script type='application/javascript'>alert('首字母只能输入一个字母');parent.window.location.reload();</script>";
            }
            //查询省份名称
            if(!empty($data['province_id'])){
                $data['province_name']   = Db::name('region')->where('region_id', $data['province_id'])->value('region_name');
            }else{
                $data['province_name']   = "默认省份";
            }
            //获取城市名称
            if(!empty($data['city_id'])){
                $data_city = Db::name('region')->field('region_name,region_code')->where('region_id', $data['city_id'])->find();
                $data['city_name'] = $data_city['region_name'];
                $data['region_code'] = $data_city['region_code'];
            }else{
                $data['city_name']      = "默认城市";
            }
            //如果省份 - 城市都为空 则为默认模板
            if(empty($data['province_id']) && empty($data['city_id'])){
                $data['is_default']     = 1;
            }
            //自定义取消规则开启 0未开启1开启
            if(empty($data['is_cancel'])){
                $data['is_cancel'] = 0;
            }
            //异地接单 0未开启1开启
            if(empty($data['remote_order'])){
                $data['remote_order'] = 0;
            }
            //自定义计价是否开启 0未开启1开启
            if(empty($data['is_valuation'])){
                $data['is_valuation'] = 0;
            }

            //$data['real_cancel_time']   = $data['real_cancel_time']*60;     //司机出发去接乘客 等待时间 - 实时
            //$data['real_arrive_time']   = $data['real_arrive_time']*60;     //司机到达乘客起点 等待时间 - 实时
            //$data['book_cancel_time']   = $data['book_cancel_time']*60;     //司机出发去接乘客 等待时间 - 预约
            //$data['book_start_time']    = $data['book_start_time']*60;      //距离预约出发时间不足 等待时间 - 预约
            //$data['book_arrive_time']   = $data['book_arrive_time']*60;     //司机到达乘客起点 等待时间 - 预约
            //$data['book_over_time']     = $data['book_over_time']*60;       //超过预约出发时间 等待时间 - 预约

            //$data['real_cancel_fee']    = $data['real_cancel_fee']*100;     //司机出发去接乘客 有责取消费用 - 实时
            //$data['real_arrive_fee']    = $data['real_arrive_fee']*100;     //司机到达乘客起点 有责取消费用 - 实时
            //$data['book_cancel_fee']    = $data['book_cancel_fee']*100;     //司机出发去接乘客 有责取消费用 - 预约
            //$data['book_start_fee']     = $data['book_start_fee']*100;      //距离预约出发时间不足 有责取消费用 - 预约
            //$data['book_arrive_fee']    = $data['book_arrive_fee']*100;     //司机到达乘客起点 有责取消费用 - 预约
            //$data['book_over_fee']      = $data['book_over_fee']*100;       //超过预约出发时间 有责取消费用 - 预约

            //时间转换成秒
            $data['start_time']         = $data['start_time']*60;           //起步时长
            $data['free_wait_time']     = $data['free_wait_time']*60;       //免费等待时长
            $data['leave_time']         = $data['leave_time']*60;           //司机出发时长
            $data['arrive_time']        = $data['arrive_time']*60;          //司机到达时长
            $data['book_remain_time']   = $data['book_remain_time']*60;     //预约时间剩余时长
            //费用转换成分
            $data['low_fee']            = $data['low_fee']*100;             //有责取消费用（低）
            $data['high_fee']           = $data['high_fee']*100;            //有责取消费用（高）
            $data['start_fee']          = $data['start_fee']*100;           //起步价
            $data['mileage_fee']        = $data['mileage_fee']*100;         //里程费
            $data['time_fee']           = $data['time_fee']*100;            //时长费
            $data['over_wait_fee']      = $data['over_wait_fee']*100;       //超时等待费
            $data['over_wait_fee_max']  = $data['over_wait_fee_max']*100;   //超时等待费上限
            //里程转换成米
            $data['start_mileage']      = $data['start_mileage']*1000;      //起步里程
            //$data['admin_id']           = session('admin_id');
            //$data['add_time']           = time();
            Db::name('price_rule')->where(['id'=>$data['id']])->update($data);
            self::priceRule($data,$data['id']);                            //计价规则 + 远途费

            //交通部数据 提交到 java接口
            $type = 'edit';
//            $this->cost_config_to_java($data,$type);
            return "<script type='application/javascript'>parent.window.location.reload();</script>";
        } else {
            //查询费用信息
            $id = input('get.id');
            $info = Db::name('price_rule')->where('id', $id)->find();
            //查询计价规则 + 远途费
            $priceList = Db::name('special_price_rule')->where('rule_id', $id)->order('id asc')->select();
            foreach ($priceList as $key=>$vale){
                //起始时间处理
                if($vale['start_time'] == 0){
                    $vale['start_time'] = '000';
                }
                if(strlen($vale['start_time']) == 3){
                    $priceList[$key]['start_time'] = substr($vale['start_time'],0,1).":".substr($vale['start_time'],1,2);
                }elseif (strlen($vale['start_time']) == 4){
                    $priceList[$key]['start_time'] = substr($vale['start_time'],0,2).":".substr($vale['start_time'],2,2);
                }
                //结束时间处理
                if(strlen($vale['end_time']) == 3){
                    $priceList[$key]['end_time'] = substr($vale['end_time'],0,1).":".substr($vale['end_time'],1,2);
                }elseif (strlen($vale['end_time']) == 4){
                    $priceList[$key]['end_time'] = substr($vale['end_time'],0,2).":".substr($vale['end_time'],2,2);
                }
            }
            //远途费
            $frPriceList = Db::name('far_price_rule')->where('rule_id', $id)->order('id asc')->select();
            //查询城市
            $where = [
                'parent_id'     => $info['province_id'],
                'region_level'  => 2
            ];
            $cityList = $this->region_model->getRegion($where,'region_id,region_name');
            $this->assign('cityList',$cityList);
            $this->assign('info', $info);
            $this->assign('priceList',$priceList);
            $this->assign('frPriceList',$frPriceList);
            return view();
        }
    }


    //提交到java 交通部信息
    public function cost_config_to_java($data,$type) {

        foreach ($data as $key => $value) {
            if ($value === '') {
                unset($data[$key]);
            }
        }

        //拼装数据
        $data_arr['CompanyId'] = "3401HMKJ8P2R";
        $data_arr['Address'] = intval($data['region_code']); //城市区划代码
        $data_arr['FareType'] = 'xmcx'; //运价类型代码 唯一性
        $data_arr['FareValidOn'] = intval(date('YmdHis', time())); //运价有效期起
        $data_arr['StartFare'] = $data['start_fee'] /100; //起步价（元）
        $data_arr['StartMile'] = $data['start_mileage'] / 1000; //起始里程
        $data_arr['UnitPricePerMile'] = $data['mileage_fee']/100;  //计程单价（按公里）单位：元
        $data_arr['UnitPricePerMinute'] = $data['time_fee']/100;  //计时单价（按分钟）单位：元

        if(in_array('早高峰',$data['name'])) {
            $key = array_search('早高峰', $data['name']);
            $ztime_start_str = '0000';
            if(!empty($data['start_timey'][$key])) {
                $ztime_start_arr = explode(':',$data['start_timey'][$key]);
                $ztime_start = $ztime_start_arr[0];
                if($ztime_start < 10) {
                    $ztime_start_str = '0'.$ztime_start.$ztime_start[1];
                }
                $data_arr['MorningPeakTimeOn'] = $ztime_start_str; // 早高峰start （HHmm）
            }
            $ztime_end_str = '0000';
            if(!empty($data['end_time'][$key])) {
                $ztime_end_arr = explode(':',$data['end_time'][$key]);
                $ztime_end = $ztime_end_arr[0];
                if($ztime_end < 10) {
                    $ztime_end_str = '0'.$ztime_end.$ztime_end_arr[1];
                }
                $data_arr['MorningPeakTimeOff'] = $ztime_end_str; // 早高峰end （HHmm）
            }

            $data_arr['PeakUnitPrice'] = ($data['start_price'][$key] - ($data['start_fee'] / 100));        //高峰时间单程加价单价
        } else {
            $data_arr['MorningPeakTimeOn'] = '0000';
            $data_arr['MorningPeakTimeOff'] = '0000';
        }

        if(in_array('晚高峰',$data['name'])) {
            $key = array_search('晚高峰', $data['name']);
            $wtime_start_str = '0000';
            if(!empty($data['start_timey'][$key])) {
                $wtime_start_arr = explode(':',$data['start_timey'][$key]);
                $wtime_start = $wtime_start_arr[0];
                if($wtime_start < 10) {
                    $wtime_start_str = '0'.$wtime_start.$wtime_start_arr[1];
                }
                $data_arr['EveningPeakTimeOn'] = $wtime_start_str; // 晚高峰start （HHmm）
            }
            $wtime_end_str = '0000';
            if(!empty($data['end_time'][$key])) {
                $wtime_end_arr = explode(':',$data['end_time'][$key]);
                $wtime_end = $wtime_end_arr[0];
                if($wtime_end < 10) {
                    $wtime_end_str = '0'.$wtime_end.$wtime_end_arr[1];
                }
                $data_arr['EveningPeakTimeOff'] = $wtime_end_str; // 晚高峰end （HHmm）
            }
        } else {
            $data_arr['EveningPeakTimeOn'] = '0000'; // 晚高峰start （HHmm）
            $data_arr['EveningPeakTimeOff'] = '0000'; // 晚高峰end （HHmm）
        }

        if(in_array('夜间费',$data['name'])) {
            $key = array_search('夜间费', $data['name']);
            $data_arr['NightPricePerMile'] = (float)$data['mileage_feey'][$key]?:0; //  夜间费 （按公里）
            $data_arr['NightPricePerMinute'] = (float)$data['time_feey'][$key]?:0; //  夜间费 （按分钟）
        } else {
            $data_arr['NightPricePerMile'] = 0;    //  夜间费 （按公里）
            $data_arr['NightPricePerMinute'] = 0;  //  夜间费 （按分钟）
        }

        $data_arr['PeakPriceStartMile'] = $data['start_mileage'] / 1000;    //高峰时间单程加价公里
        $data_arr['LowSpeedPricePerMinute'] = 0;   //低速计价加价 按分钟 单位：元

        $data_arr['OtherPrice'] = ($data['over_wait_fee']/100)?:0;  //其他费用  超时等待费

        $data_arr['UpPrice'] = 0;                                   //单程加价单价
        $data_arr['UpPriceStartMile'] = 0;                          //单程加价公里
        $data_arr['State'] = 1;
        if($type == 'add') {
            $data_arr['Flag'] = 1; //添加
        } else {
            $data_arr['Flag'] = 2; //修改
        }
        $data_arr['UpdateTime'] = (int)date('YmdHis', time());

        //交通部
        $host = Env::get('javaTraffic'.ENV.'_host')."/46";
        $res = Tools::request_post($host, json_encode($data_arr));
        if($res == 200) {
            echo json_encode(array('code'=>1,'msg'=>'success'));
            exit();
        } else {
            echo json_encode(array('code'=>0,'msg'=>'error'));
            exit();
        }
    }

    //查看计价信息
    public function look() {
        //查询费用信息
        $id = input('get.id');
        $info = Db::name('price_rule')->where('id', $id)->find();
        //查询计价规则 + 远途费
        $priceList = Db::name('special_price_rule')->where('rule_id', $id)->order('id asc')->select();
        foreach ($priceList as $key=>$vale){
            //起始时间处理
            if($vale['start_time'] == 0){
                $vale['start_time'] = '000';
            }
            if(strlen($vale['start_time']) == 3){
                $priceList[$key]['start_time'] = substr($vale['start_time'],0,1).":".substr($vale['start_time'],1,2);
            }elseif (strlen($vale['start_time']) == 4){
                $priceList[$key]['start_time'] = substr($vale['start_time'],0,2).":".substr($vale['start_time'],2,2);
            }
            //结束时间处理
            if(strlen($vale['end_time']) == 3){
                $priceList[$key]['end_time'] = substr($vale['end_time'],0,1).":".substr($vale['end_time'],1,2);
            }elseif (strlen($vale['end_time']) == 4){
                $priceList[$key]['end_time'] = substr($vale['end_time'],0,2).":".substr($vale['end_time'],2,2);
            }
        }
        //远途费
        $frPriceList = Db::name('far_price_rule')->where('rule_id', $id)->order('id asc')->select();
        //查询城市
        $where = [
            'parent_id'     => $info['province_id'],
            'region_level'  => 2
        ];
        $cityList = $this->region_model->getRegion($where,'region_id,region_name');
        $this->assign('cityList',$cityList);
        $this->assign('info', $info);
        $this->assign('priceList',$priceList);
        $this->assign('frPriceList',$frPriceList);
        return view();
    }

    //城市运营状态 + 取消订单扣费规则 + 计价规则 开启操作
    public function is_open(){
        $value = input('post.value');
        $id = input('post.id');
        $type = input('post.type');
        if($type == 1){         //城市运营状态
            $res = Db::name('price_rule')->where('id',$id)->update(['is_use'=>$value]);
        }elseif($type == 2){    //取消订单扣费规则
            $res = Db::name('price_rule')->where('id',$id)->update(['is_cancel'=>$value]);
        }elseif($type == 3){    //计价规则
            $res = Db::name('price_rule')->where('id',$id)->update(['is_valuation'=>$value]);
        }elseif ($type==5){ //异地接单
            $res = Db::name('price_rule')->where('id',$id)->update(['remote_order'=>$value]);
        }
        if($res){
            return json(array(
                'status' => 1,
                'msg' => '处理成功',
            ));
        }else{
            return json(array(
                'status' => 0,
                'msg' => '处理失败',
            ));
        }
    }

    //特殊时段 + 远途计价数据入库
    public function priceRule($data = [],$rule_id=''){
    //特殊时段计价规则处理
        $result = [];
        Db::name('special_price_rule')->where('rule_id',$rule_id)->delete();    //计价
        Db::name('far_price_rule')->where('rule_id',$rule_id)->delete();        //远途费
        foreach ($data['name'] as $key=>$value){
            //判断不能为空 处理
            if($data['end_time'][$key] == '0:00'){
                $data['end_time'][$key] = '24:00';
            }
            if(!empty($value) && !empty($data['start_timey'][$key]) && !empty($data['end_time'][$key]) && !empty($data['start_price'][$key]) && !empty($data['mileage_feey'][$key]) && !empty($data['time_feey'][$key]) && !empty($data['over_time_fee'][$key])){
                $result[] = [
                    'name'          => $value,
                    'start_time'    => str_replace(":","",$data['start_timey'][$key]),
                    'end_time'      => str_replace(":","",$data['end_time'][$key]),
                    'start_price'   => $data['start_price'][$key]*100,
                    'mileage_fee'   => $data['mileage_feey'][$key]*100,
                    'time_fee'      => $data['time_feey'][$key]*100,
                    'over_time_fee' => $data['over_time_fee'][$key]*100,
                    'rule_id'       => $rule_id,
                    'is_use'        => 1
                ];
            }
        }
        Db::name('special_price_rule')->insertAll($result);
        //远途费操作
        $yuantuArr = [];
        foreach ($data['start_mileagey'] as $key=>$value){
            if(!empty($value) && !empty($data['end_mileagey'][$key]) && !empty($data['yuantu_mileage_fee'][$key])){
                $yuantuArr[] = [
                    'start_mileage' => $value*1000,
                    'end_mileage'   => $data['end_mileagey'][$key]*1000,
                    'mileage_fee'   => $data['yuantu_mileage_fee'][$key]*100,
                    'rule_id'       => $rule_id
                ];
            }
        }
        Db::name('far_price_rule')->insertAll($yuantuArr);
    }

}
